﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using HardwareUtils;
using Lap.Collections;
using Lap.Extensions.Core;

namespace PpSmsSender
{
    class ModemHW
    {
        public static Dictionary<string, SmsSender.ModemPortInfo> ModemPortInfos (List<Regex> patterns)
        {
            var modemPortInfos = new Dictionary<string, SmsSender.ModemPortInfo>();

            PnPDevices.GetDevices("Service", "hwdatacard")
                .Where(dev => patterns.Any(pat => pat.IsMatch(dev.Description)))
                .ForEach(dev =>
                             {
                                 MatchCollection matches = patterns.Select(pat => pat.Matches(dev.Description)).First(mtchs => mtchs.Count > 0);
                                 string com = matches[0].Groups["portname"].Value;
                                 string comNumber = matches[0].Groups["comnumber"].Value;
                                 if (com.IsNullOrWhiteSpace() && !comNumber.IsNullOrWhiteSpace())
                                 {
                                     com = "COM" + comNumber;
                                 }
                                 if (!com.IsNullOrWhiteSpace())
                                 {
                                     modemPortInfos[com.ToUpper()] = new SmsSender.ModemPortInfo {ComPort = com.ToUpper(), DevInfo = dev};
                                 }
                             });

            //patterns.Add(new Regex("modem",RegexOptions.IgnoreCase)); //test finding any modem
            PnPDevices.GetPorts()
                .Where(port => patterns.Any(pat => pat.IsMatch(port.Description)))
                .ForEach(port =>
                             {
                                 string com = port.DeviceID;
                                 if (!com.IsNullOrWhiteSpace() && !modemPortInfos.ContainsKey(com.ToUpper()))
                                 {
                                     modemPortInfos[com.ToUpper()] = new SmsSender.ModemPortInfo {ComPort = com.ToUpper(), DevInfo = port};
                                 }
                             });
            return modemPortInfos;
        }
    }
}
